import { createRouter, createWebHistory } from "vue-router"
//导入store
import { useUserStore } from "@/stores/users.js"
//导入Http
import { Http } from "../http/users"
//导入消息提示
import { ElMessage } from "element-plus"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录页面
    {
      path: "/",
      name: "login",
      component: () => import("../views/ItsLogin/ItsLogin.vue"),
    },
    {
      path: "/home",
      name: "home",
      component: () => import("../views/ItsHome/ItsHome.vue"),
    },
    //用户管理页面
    {
      path: "/users",
      name: "users",
      component: () => import("../views/ItsUsers/ItsUsers.vue"),
      redirect: { name: "traffic" },
      children: [
        //交通部门管理
        {
          path: "trafficMember",
          name: "traffic",
          component: () => import("../views/ItsUsers/children/ItsTraffic.vue"),
        },
        // 普通用户管理
        {
          path: "normalMember",
          name: "normal",
          component: () => import("../views/ItsUsers/children/ItsNormal.vue"),
        },
      ],
    },
    {
      path: "/notice",
      name: "notice",
      component: () => import("../views/ItsNotice/ItsNotice.vue"),
    },
    {
      path: "/middle/addevent",
      name: "middleaddevent",
      component: () => import("../views/ItsAddEvent/ItsAddEvent.vue"),
    },
    {
      path: "/event",
      name: "event",
      component: () => import("../views/ItsEvent/ItsEvent.vue"),
    },
    {
      path: "/monitor",
      name: "monitor",
      component: () => import("../views/ItsMonitor/ItsMonitor.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      component: () => import("../views/NotFound.vue"),
    },
  ],
})
//全局导航守卫
router.beforeEach(async (to, from) => {
  const store = useUserStore()
  // console.log(store.user.token)
  if (store.user.token == "" && to.name !== "login") {
    //当没有token时
    return { name: "login" }
  } else {
    //当有token时,验证token是否有效
    let data = await Http.getLogin()
    if (data.code == 200) {
      return true
    } else {
      if (to.name !== "login") {
        ElMessage.error("请重新登录")
        return { name: "login" }
      }
    }
  }
})
export default router
